//
//  CHComplaintListController.m
//  CarFile
//
//  Created by 陈浩 on 2017/5/26.
//  Copyright © 2017年 陈浩. All rights reserved.
//

#import "CHComplaintListController.h"
#import "CHComplaintDetailController.h"
#import "CHWXJLDetailsViewController.h"
#import "CHComplainListFrame.h"
#import "CHComplainListCell.h"
#import "CHTSTableViewCell.h"
#import "CHMenuView.h"
#import "QZTopTextView.h"
#import "CHPresentView.h"
#import "CHDBTableViewCell.h"
#define KHEIGHT 40
@interface CHComplaintListController ()<UITableViewDelegate,UITableViewDataSource,CHMenuViewDelegate,CHDBTableViewCellDelegate,CHPresentViewDelegate>
@property (nonatomic ,strong) NSMutableArray *datas;
@property (nonatomic ,strong) NSMutableArray *wdbDatas;
@property (nonatomic ,strong) CHMenuView *menuView;
@property (nonatomic ,strong) CHPresentView *presentView;
@property (nonatomic ,strong) UITableView *ts_tableView;
@property (nonatomic ,strong) UITableView *wdb_tableView;
@property (nonatomic ,strong) UIScrollView *mainScrollView;
@property (nonatomic ,strong) UIButton *coverBtn;
@property (nonatomic ,assign) int page;
@property (nonatomic ,assign) int index;
@property (nonatomic ,assign) NSInteger currentIndex;
@property (nonatomic ,assign) BOOL isLoad;
@property (nonatomic ,copy) NSString *companyid;
@end

@implementation CHComplaintListController
-(NSMutableArray *)datas{
    
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}

-(NSMutableArray *)wdbDatas{
    if (!_wdbDatas) {
        _wdbDatas = [NSMutableArray array];
    }
    return _wdbDatas;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"投诉列表";
//    self.title = [NSString stringWithFormat:@"投诉列表(%@)",self.areacn];

    _isLoad = NO;
    
    [self setupMenuView];

    [self setupMainScrollView];
 

}

-(void)setupMenuView{
    
    NSArray *titles = @[@"全部投诉",@"未督办"];
    CHMenuView *menuView =[[ CHMenuView alloc] initWithFrame:CGRectMake(0, 0, UIScreenW, 40) withTitles:titles];
    menuView.delegate = self;
    menuView.bgColor = [UIColor colorWithHexString:@"eeeef0" alpha:1.0f];
    [self.view addSubview:menuView];
    self.menuView = menuView;
    
    

}




-(void)setupMainScrollView{
    
    
    UIScrollView *mainScrollview = [[UIScrollView alloc] initWithFrame:CGRectMake(0,  CGRectGetMaxY(self.menuView.frame), UIScreenW, UIScreenH - CGRectGetMaxY(self.menuView.frame) -64 )];
    mainScrollview.delegate = self;
    mainScrollview.pagingEnabled = YES;
    mainScrollview.scrollEnabled = YES;
    mainScrollview.bounces = NO;
    mainScrollview.showsHorizontalScrollIndicator = NO;
    mainScrollview.showsVerticalScrollIndicator = NO;
    //    mainScrollview.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth;
    [self.view addSubview:mainScrollview];
    self.ts_tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, UIScreenW, mainScrollview.h)];
    self.ts_tableView.backgroundColor = [UIColor colorWithHexString:@"111111" alpha:0.1f];
    self.ts_tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.ts_tableView.delegate = self;
    self.ts_tableView.dataSource = self;
    // 下拉刷新
    self.ts_tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        
        [self getTSData];
    }];
    self.ts_tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        [self loadMoreTSData];
    }];
    self.ts_tableView.mj_footer.automaticallyHidden = YES;
    [mainScrollview addSubview:self.ts_tableView];
    [self.ts_tableView.mj_header beginRefreshing];
    
    
    self.wdb_tableView = [[UITableView alloc] initWithFrame:CGRectMake(UIScreenW, 0, UIScreenW, mainScrollview.h)];
    self.wdb_tableView.backgroundColor = [UIColor colorWithHexString:@"111111" alpha:0.1f];
    // 下拉刷新
    self.wdb_tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    self.wdb_tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        
        [self getWDBData];
        
    }];
    self.wdb_tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreWDBData];
    }];
    self.wdb_tableView.mj_footer.automaticallyHidden = YES;
    self.wdb_tableView.delegate = self;
    self.wdb_tableView.dataSource = self;
    [mainScrollview addSubview:self.wdb_tableView];
    
    mainScrollview.contentSize = CGSizeMake(UIScreenW *2, 0);
    self.mainScrollView = mainScrollview;
}


-(void)getWDBData{
    
    _index = 1;
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = self.areaid;
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:self.areaid encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"flag"] = @"0";
    params[@"companyid"] = self.companyid;
    params[@"pagenum"] = [NSString stringWithFormat:@"%d",_index];
    params[@"pagesize"] = @"20";
    params[@"start"] = self.startTime;
    params[@"end"] = self.endTime;
    
    //    lcipappgovcomplaintlist
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovsupervisorlist" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        NSLog(@"未督办结果%@",result);
        [self.wdbDatas removeAllObjects];
        [self.wdb_tableView.mj_header endRefreshing];
        if ([result[@"code"] isEqualToString:@"1"]) {
            
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                CHComplainListModel *model = [CHComplainListModel objectWithKeyValues:dict];
                CHComplainListFrame *listFrm = [[CHComplainListFrame alloc] init];
                listFrm.model = model;
                [self.wdbDatas addObject:listFrm];
            }
            self.wdb_tableView.placeholderImage = @"data_null";
            self.wdb_tableView.placeholder = @"暂时没有数据哦~";
            [self.wdb_tableView reloadData];
        }
    }];
}

-(void)loadMoreWDBData{
    
    _index++;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = self.areaid;
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:self.areaid encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"flag"] = @"0";
    params[@"companyid"] = self.companyid;
    params[@"pagenum"] = [NSString stringWithFormat:@"%d",_index];
    params[@"pagesize"] = @"20";
    params[@"start"] = self.startTime;
    params[@"end"] = self.endTime;
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovsupervisorlist" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {

        [self.wdb_tableView.mj_footer endRefreshing];
        if ([result[@"code"] isEqualToString:@"1"]) {
            
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                CHComplainListModel *model = [CHComplainListModel objectWithKeyValues:dict];
                CHComplainListFrame *listFrm = [[CHComplainListFrame alloc] init];
                listFrm.model = model;
                [self.wdbDatas addObject:listFrm];
            }
            
            [self.wdb_tableView reloadData];
        }
    }];
    
}



-(void)getTSData{
    _page = 1;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = self.areaid;
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"companyid"] = self.companyid;
    params[@"sign"] = [DESCript encrypt:self.areaid encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"pagenum"] = [NSString stringWithFormat:@"%d",_page];

    params[@"pagesize"] = @"20";
    params[@"start"] = self.startTime;
    params[@"end"] = self.endTime;
 
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovcomplaintlist" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        NSLog(@"全部投诉%@",result);
        [self.datas removeAllObjects];
        [self.ts_tableView.mj_header endRefreshing];
        if ([result[@"code"] isEqualToString:@"1"]) {
            
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                
                CHComplainListModel *model = [CHComplainListModel objectWithKeyValues:dict];
                CHComplainListFrame *listFrm = [[CHComplainListFrame alloc] init];
                listFrm.model = model;
                
                [self.datas addObject:listFrm];
            }
            self.ts_tableView.placeholderImage = @"data_null";
            self.ts_tableView.placeholder = @"暂时没有数据哦~";
            [self.ts_tableView reloadData];
            
        }
     
    }];
}


-(void)loadMoreTSData{
    
    _page++;
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = self.areaid;
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:self.areaid encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"pagenum"] = [NSString stringWithFormat:@"%d",_page];
    params[@"pagesize"] = @"20";
    params[@"start"] = self.startTime;
    params[@"end"] = self.endTime;
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovcomplaintlist" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {

        [self.ts_tableView.mj_footer endRefreshing];
        if ([result[@"code"] isEqualToString:@"1"]) {
            
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                CHComplainListModel *model = [CHComplainListModel objectWithKeyValues:dict];
                CHComplainListFrame *listFrm = [[CHComplainListFrame alloc] init];
                listFrm.model = model;
                [self.datas addObject:listFrm];
            }
            
            [self.ts_tableView reloadData];
            
        }
    }];
    
    
}

-(void)didBtnClickWithTag:(NSInteger)tag cellIndex:(NSInteger)index{
    _currentIndex = index;

    if (tag == 100) {        //   督办

        UIButton *coverBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, UIScreenW, UIScreenH - 64)];
        coverBtn.backgroundColor = [UIColor blackColor];
        coverBtn.alpha = 0.7;
        [coverBtn addTarget:self action:@selector(coverBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:coverBtn];
        self.coverBtn = coverBtn;
        
        CHPresentView *presentView = [[CHPresentView alloc] initWithFrame:CGRectMake(0, 0,UIScreenW *0.7, 250)];
        presentView.delegate = self;
        presentView.center = CGPointMake(self.view.center.x, self.view.center.y-64);
        [self.view addSubview:presentView];
        self.presentView = presentView;
        
    }else{
        
        CHComplainListFrame *listFrm = self.wdbDatas[index];
        CHWXJLDetailsViewController *VC  =[[CHWXJLDetailsViewController alloc] init];
        VC.listModel = listFrm.model;
        [self.navigationController pushViewController:VC animated:YES];
        
    }
}


-(void)coverBtnClick{
    
    [self.presentView removeFromSuperview];
    [self.coverBtn removeFromSuperview];
}


-(void)didSumitToResultStr:(NSString *)resultStr{
    
    [MBProgressHUD showMessage:@"正在督办中···"];
    CHComplainListFrame *listFrm = self.wdbDatas[_currentIndex];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = self.areaid;
    params[@"userflag"] = [Util getValue:@"userflag"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:listFrm.model.evaluateid encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"evaluateid"] = listFrm.model.evaluateid;
    params[@"content"] = resultStr;

    [[Globle getInstance].service requestWithServiceName:@"lcipappgovsupervise" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
    
        [MBProgressHUD hideHUD];
        if ([result[@"code"] isEqualToString:@"1"]) {
            [self getWDBData];
            [MBProgressHUD showSuccess:result[@"status"]];
            [self.presentView removeFromSuperview];
            [self.coverBtn removeFromSuperview];
        }
    }];
    
}


#pragma mark - UIScrollViewDelegate
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    if (scrollView == self.mainScrollView) {
        
        int tag = (int)scrollView.contentOffset.x/self.view.size.width +100 ;
        
        UIButton *btn = (UIButton *)[self.menuView viewWithTag:tag];
        
        
        [self.menuView titleBtnClick:btn];
    }
    
}


-(void)CHMenuView:(CHMenuView *)menuView didBtnClickWithTag:(NSInteger)tag{
    
   
    [self.mainScrollView setContentOffset:CGPointMake(( tag - 100) *UIScreenW, 0) animated:YES];
    if (tag == 101) {
        if (!_isLoad) {
            [self.wdb_tableView.mj_header beginRefreshing];
            _isLoad = YES;
        }
    }
}



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (tableView == self.ts_tableView) {
        return self.datas.count;
    }
    return self.wdbDatas.count;
    
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.ts_tableView) {
        
        CHTSTableViewCell *cell = [CHTSTableViewCell cellForTableView:tableView];
        cell.complainListFrm = self.datas[indexPath.row];
        
        return cell;
    }else{
        
        CHDBTableViewCell *cell = [CHDBTableViewCell cellForTableView:tableView];
        cell.delegate = self;
        cell.tag = indexPath.row;
        cell.complainListFrm = self.wdbDatas[indexPath.row];
        
        
        return cell;
    }
    
  
    
    
    return nil;
    
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.ts_tableView) {
        return 100;
    }
    return [self.wdbDatas[indexPath.row] cellHeight] -20;

    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if (tableView == self.ts_tableView) {

        id obj = [LongriseRouter openURL:@"CHComplaintDetailController"];
        if(obj && [obj isKindOfClass:[UIViewController class]])
        {
            UIViewController *vc = obj;
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        //判断该类是否可以传参数
        if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
        {
            id<LongriseRouterDelegater> delegater = obj;
            if(delegater)
            {
                
                NSMutableDictionary *params = [NSMutableDictionary dictionary];
                params[@"areaid"] = self.areaid;
                params[@"complainListFrm"] = self.datas[indexPath.row];
                //进行传值，传入统一的block以供B进行回调
                [delegater setParams:params block:^(id obj) {
                    
                    
                }];
            }
        }
        
    }
    
}

//
//补全分割线
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)])
    {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell  respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)])
    {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)])
    {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark LongriseRouterDelegater代理回调方法
-(void)setParams:(id)obj block:(LongriseRouterBlock)block
{
    
    if (obj && [obj isKindOfClass:[NSMutableDictionary class]]) {
        
        NSMutableDictionary *dict = obj;
        self.companyid = dict[@"companyid"];
        self.areaid = dict[@"areaid"];
        self.areacn = dict[@"areacn"];
        self.startTime = dict[@"starttime"];
        self.endTime = dict[@"endtime"];
        
    }
}



@end
